package com.smt.modules.app.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;

/**
 * @author zhangyi
 * @date 2018/10/13 11:34
 */
@Slf4j
public class FileSizeUtil {

    public static final int MB_SIZE = 1024 * 1024;

    public static final String KB = "KB";

    public static final String MB = "MB";

    /**
     * 这里计算两种大小   KB MB
     *
     * @param fileUrl
     * @return
     */
    public static String getFileSize(String fileUrl) {
        URL url = null;
        StringBuffer fs = new StringBuffer();
        HttpURLConnection con = null;
        try {
            if (fileUrl != null && !fileUrl.equals("null")) {
                url = new URL(fileUrl);
                con = (HttpURLConnection) url.openConnection();
                double contentLength = (double) con.getContentLength() / MB_SIZE;
                if (con.getResponseCode() >= 400) {
                    log.error("服务器响应错误 CODE:{}", con.getResponseCode());
                    return null;
                }
                DecimalFormat df = new DecimalFormat("#.00");
                if (contentLength < 1.0) {
                    fs.append(df.format(contentLength * 1024))
                            .append(KB);
                } else {
                    fs.append(df.format(contentLength))
                            .append(MB);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(con != null) {
                con.disconnect();
            }
        }
        return fs.toString()+"";
    }

    /**
     * 返回文件大小数字形式（/MB）
     *
     * @param fileUrl
     * @return
     */
    public static double getFileSizeToNumber(String fileUrl) {
        if (!("null".equals(fileUrl)) && !(fileUrl == null)) {
            String fileSizeStr = getFileSize(fileUrl);
            if (StringUtils.contains(fileSizeStr, KB)) {
                String trim = fileSizeStr.replace(KB, "").trim();
                Double size = Double.valueOf(Double.parseDouble(trim) / 2014);
                return size;
            } else if (StringUtils.contains(fileSizeStr, MB)) {
                String trim = fileSizeStr.replace(MB, "").trim();
                Double aDouble = Double.valueOf(trim);
                return aDouble;
            }
        }
        return 0.0;
    }
}
